package com.woyou.fragment.shop;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.bean.MarkUp;
import com.woyou.bean.UserInfo;
import com.woyou.bean.WYList;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.UpdateLadderFeeReq;
import com.woyou.component.SuperUI;
import com.woyou.fragment.SuperFragment;
import com.woyou.model.rpc.ShopModel;
import com.woyou.utils.FormatTools;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 外送阶梯价界面
 * 
 * @author zhou.ni
 *
 */
public class DeliveryFeeFragment extends SuperFragment implements OnClickListener {
	private HomeActivity homeActivity;
	private View layout_deliveryfee;
	private RelativeLayout layout_deliveryfee_bg;

	// 功能
	private LinearLayout layout_deliveryfee_panel;
	private RelativeLayout layout_deliveryfee_cancel;
	private RelativeLayout layout_deliveryfee_submit;
	
	private LinearLayout deliverContainerView;
	private WYList<MarkUp> copyList = new WYList<MarkUp>();  		//本地复制的阶梯价数据,实现序列化接口
	private List<MarkUp> waitUpdateList = new ArrayList<MarkUp>();  //等待更新的数据 
	
	private List<MarkUp> removeList = new ArrayList<MarkUp>();		//删除的阶梯价数据
	
	private TextView addText;										//添加一条阶梯价按钮


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout_deliveryfee = inflater.inflate(R.layout.layout_deliveryfee, container, false);
		homeActivity=(HomeActivity)getActivity();
		return layout_deliveryfee;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
	}
	
	@Override
	public void onHiddenChanged(boolean hidden) {
		if (!hidden) {
			fullMarkUpTime();
		} else {
			layout_deliveryfee_panel.setVisibility(View.GONE);
		}
	}
	
	/**
	 * 初始化控件
	 */
	public void initView() {
		layout_deliveryfee_bg=(RelativeLayout)layout_deliveryfee.findViewById(R.id.layout_deliveryfee_bg);
		deliverContainerView = (LinearLayout) layout_deliveryfee.findViewById(R.id.deliverfee_list);
		// 保存、提交面板
		layout_deliveryfee_panel = (LinearLayout) layout_deliveryfee.findViewById(R.id.layout_deliveryfee_panel);
		layout_deliveryfee_cancel = (RelativeLayout) layout_deliveryfee.findViewById(R.id.layout_deliveryfee_cancel);
		layout_deliveryfee_submit = (RelativeLayout) layout_deliveryfee.findViewById(R.id.layout_deliveryfee_submit);
		//关闭输入法，监听这些面板
		layout_deliveryfee_bg.setOnClickListener(this);
		layout_deliveryfee_cancel.setOnClickListener(this);
		layout_deliveryfee_submit.setOnClickListener(this);
		
		fullMarkUpTime();
	}
	
	/**
	 * 填充外送阶梯价数据
	 */
	private void fullMarkUpTime() {
		if ( deliverContainerView!=null ) {
			deliverContainerView.removeAllViews();
		}
		
		final WYList<MarkUp> list = (WYList<MarkUp>) aCache.getAsObject("deliverfee");
		if ( list!=null && list.size()>0 ) {
			//修改左侧抽屉的外送费
			String prompt = FormatTools.String2Money(list.get(0).getSendUpFee()+"") + "元起送 / ";
			homeActivity.menuView.menuSendup.setText(prompt);
			copyList.clear();
			waitUpdateList.clear();
			removeList.clear();
			copyList.addAll(list);
			
			for (int i = 0; i < list.size(); i++) {
				final MarkUp changeItem = list.get(i);
				View itemView = View.inflate(homeActivity, R.layout.item_markup_lv, null);
				final EditText rangeText = (EditText) itemView.findViewById(R.id.markup_range);
				final EditText deliverFeeText = (EditText) itemView.findViewById(R.id.markup_delivefee);
				final EditText sendupFeeText = (EditText) itemView.findViewById(R.id.markup_sendfee);
				ImageView delete = (ImageView) itemView. findViewById(R.id.deliverfee_delete);	
				
				//删除一条记录
				itemView.setTag(changeItem);
				delete.setTag(itemView);
				delete.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						View parent = (View) v.getTag();
						MarkUp obj = (MarkUp) parent.getTag();
						copyList.remove(obj);			//在复制数据中移除 这条数据
						redeceDeliverFeeItem(obj, parent);
					}
				});
				
				if ( i==0 ) {
					delete.setVisibility(View.GONE);
				} else {
					delete.setVisibility(View.VISIBLE);
				}
				
				rangeText.setText(FormatTools.String2Money(changeItem.getRange()/1000+""));
				deliverFeeText.setText(FormatTools.String2Money(changeItem.getDeliverFee()+""));
				sendupFeeText.setText(FormatTools.String2Money(changeItem.getSendUpFee()+""));
				
				rangeText.addTextChangedListener(new TextWatcher() {							//公里数的监听
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
					}
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
					}
					@Override
					public void afterTextChanged(Editable s) {
						rangeText.setSelection( s.toString().length());
						
						if ( !s.toString().equals(FormatTools.String2Money(changeItem.getRange()/1000+"")) ) {
							layout_deliveryfee_panel.setVisibility(View.VISIBLE);
						} else {
							layout_deliveryfee_panel.setVisibility(View.GONE);
						}
						
						if ( s.toString().length()>6 ) {
							rangeText.setText( s.toString().substring(0, 6) );
						}
						
					}
				});
				deliverFeeText.addTextChangedListener(new TextWatcher() {					//起送价的监听
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
					}
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
					}
					@Override
					public void afterTextChanged(Editable s) {
						deliverFeeText.setSelection( s.toString().length());
						
						if ( !s.toString().equals(FormatTools.String2Money(changeItem.getDeliverFee()+"")) ) {
							layout_deliveryfee_panel.setVisibility(View.VISIBLE);
						} else {
							layout_deliveryfee_panel.setVisibility(View.GONE);
						}
						
						if ( s.toString().length()>6 ) {
							deliverFeeText.setText( s.toString().substring(0, 6) );
						}
						
					}
				});
				sendupFeeText.addTextChangedListener(new TextWatcher() {						//外送费的监听
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
					}
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
					}
					@Override
					public void afterTextChanged(Editable s) {
						sendupFeeText.setSelection( s.toString().length());
						
						if ( !s.toString().equals(FormatTools.String2Money(changeItem.getSendUpFee()+"")) ) {
							layout_deliveryfee_panel.setVisibility(View.VISIBLE);
						} else {
							layout_deliveryfee_panel.setVisibility(View.GONE);
						}
						
						if ( s.toString().length()>6 ) {
							sendupFeeText.setText( s.toString().substring(0, 6) );
						}
						
					}
				});
				
				deliverContainerView.addView(itemView, i);
			}
			
			layout_deliveryfee_panel.setVisibility(View.GONE);
			if ( list.size()<8 ) {
				addView();
			}
			
		}
	}
	
	/**
	 * 增加一个新增区段按钮
	 */
	private void addView() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		params.setMargins(100, 30, 100, 20);
		
		addText = new TextView(homeActivity);
		addText.setBackgroundResource(R.drawable.deliver_fee_add_bg);
		addText.setHeight(100);
		addText.setWidth(400);
		addText.setText(" + 新增区段");
		addText.setTextColor(Color.WHITE);
		addText.setTextSize(getResources().getDimension(R.dimen.sp30));
		addText.setGravity(Gravity.CENTER);
		if ( deliverContainerView!=null ) {
			deliverContainerView.addView(addText, params);
		}
		
		addText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addDeliverFeeItem();
			}
		});
		
	}

	/**
	 * 更改阶梯价数据
	 */
	private void updateLadderFeeData() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					if ( judgeInputCorrect() ) {
						UpdateLadderFeeReq updateLadderFeeReq = new UpdateLadderFeeReq();
						UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
						if ( userInfo!=null ){
							updateLadderFeeReq.setsId(userInfo.getsId());
							updateLadderFeeReq.setPwd(userInfo.getPwd());
						}
						updateLadderFeeReq.setMarkUpList(waitUpdateList);
						final Result<List<MarkUp>> result = ShopModel.getInstance(homeActivity).updateLadderFee(updateLadderFeeReq);
						if (result != null && result.getCode() == 1) {
							homeActivity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									SuperUI.openToast(homeActivity, result.msg);
									List<MarkUp> upList = result.getData();						  //把阶梯价存入缓存
									if ( upList!=null ) {
										WYList<MarkUp> upWyList = new WYList<MarkUp>();
										upWyList.addAll(upList);
										aCache.put("deliverfee", upWyList);     			
									}
									fullMarkUpTime();
								}
							});
						} else if( result != null && result.code==-3 ) {
							homeActivity.homeController.exitLogin();
						} else {
							homeActivity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									SuperUI.openToast(homeActivity, "保存失败,请重试");
								}
							});
						}
					} 
				} catch (Exception e) {
					homeActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							SuperUI.openToast(homeActivity, "保存失败,请重试");
						}
					});
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}
	
	/**
	 * 对list进行排序
	 */
	private void sortList(){
		for (int i = 0; i < copyList.size()-1; i++) {  			//最多做n-1趟排序
			for (int j = 0; j < copyList.size()-i-1; j++) {
				MarkUp m1 = copyList.get(j);
				MarkUp m2 = copyList.get(j+1);
				if ( m2.getRange() < m1.getRange() ){
//					MarkUp m = m2;
//					m2 = m1;
//					m1 = m;
					copyList.set(j, m2);
					copyList.set(j+1, m1);
				}
				
			}
			
		}
	}
	
	/**
	 * 判断输入是否合法
	 * @return
	 */
	private boolean judgeInputCorrect(){
		
		waitUpdateList.clear();
		waitUpdateList.addAll(removeList);
		
		List<MarkUp> changeList = new ArrayList<MarkUp>();		
		
		View lastView = deliverContainerView.getChildAt(deliverContainerView.getChildCount()-1);  //获取最后一条View
		int length = 0;
		if ( lastView instanceof TextView ) {
			length = deliverContainerView.getChildCount()-1;
		} else {
			length = deliverContainerView.getChildCount();
		}
		
		for (int i = 0; i < length; i++) {
			View view = deliverContainerView.getChildAt(i);
			EditText rangeText = (EditText) view.findViewById(R.id.markup_range);
			EditText deliverFeeText = (EditText) view.findViewById(R.id.markup_delivefee);
			EditText sendupFeeText = (EditText) view.findViewById(R.id.markup_sendfee);
			String range = rangeText.getText().toString();
			String deliverFee = deliverFeeText.getText().toString();
			String sendupFee = sendupFeeText.getText().toString();
			
			if ( TextUtils.isEmpty(range) ) {
				homeActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						SuperUI.openToast(homeActivity, "公里数不能为空、不能为0");
					}
				});
				return false;
			} else if ( Float.parseFloat(range)>99 ) {
				homeActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						SuperUI.openToast(homeActivity, "公里数不能大于99");
					}
				});
				return false;
			} else if ( "0".equals(FormatTools.String2Money(range)) ) {
				homeActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						SuperUI.openToast(homeActivity, "公里数不能为空、不能为0");
					}
				});
				return false;
			} 
			
			MarkUp up = copyList.get(i);
			String r = FormatTools.String2Money(up.getRange()/1000+"");
			String d = FormatTools.String2Money(up.getDeliverFee()+"");
			String s = FormatTools.String2Money(up.getSendUpFee()+"");
			if ( !TextUtils.isEmpty(up.getfId()) ){
				if ( !r.equals(range) || !d.equals(deliverFee) || !s.equals(sendupFee) ) {
					up.setType(3);
				} else {
					up.setType(0);
				}
			} else {
				up.setType(1);
			}
			
			try {
				up.setRange(Float.parseFloat(range)*1000);
			} catch (Exception e) {
				up.setRange(500);
			}
			
			if ( !TextUtils.isEmpty(deliverFee) ) {
				try {
					up.setDeliverFee(Float.parseFloat(deliverFee));
				} catch (Exception e) {
					up.setDeliverFee(0);
				}
			} else {
				up.setDeliverFee(0);
			}
			
			if ( !TextUtils.isEmpty(sendupFee) ) {
				try {
					up.setSendUpFee(Float.parseFloat(sendupFee));
				} catch (Exception e) {
					up.setSendUpFee(0);
				}
			} else {
				up.setSendUpFee(0);
			}
			
			waitUpdateList.add(up);
			changeList.add(up);
		}
		
		if ( changeList.size()> 1 ) {
			for (int i = 0; i < changeList.size()-1; i++) {
				MarkUp m1 = changeList.get(i);
				MarkUp m2 = changeList.get(i+1);
//				if( m2.getRange()>m1.getRange() ) {
//					;
//				} else {
//					return false;
//				}
//				if ( i+2 == changeList.size() ) {
//					if( m2.getRange()>m1.getRange() ) {
//						return true;
//					} else {
//						return false;
//					}
//				}
				
				if ( m2.getRange()==m1.getRange() ) {
					homeActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							SuperUI.openToast(homeActivity, "公里数不能重复");
						}
					});
					return false;
				}
				if ( i+2 == changeList.size() ) {
					if( m2.getRange() == m1.getRange() ) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "公里数不能重复");
							}
						});
						return false;
					} else {
						return true;
					}
				}
				
			}
		} else {
			return true;
		}
		
		return false;
	}
	
	/**
	 * 判断该EditText 是否一个整数或者是正浮点数
	 * 
	 * @param et
	 * @return true是 false否
	 */
	public boolean isNumber(String str) {
		if (TypeJudgeTools.isNull(str)) {
			return false;
		}
		boolean isPN = TypeJudgeTools.isPositiveNumber(str);
		boolean isFPN = TypeJudgeTools.isFloatingPointNumber(str);
		if (!isPN && !isFPN) {
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_deliveryfee_bg:
			homeActivity.homeController.hideInputMethod();
			break;
		case R.id.layout_deliveryfee_cancel:		// 重置数据
			fullMarkUpTime();
			break;
		case R.id.layout_deliveryfee_submit:		// 更改数据
			updateLadderFeeData();
			break;
		}
	}	
	
	private MarkUp addItem;
	/**
	 * 增加一条阶梯价
	 */
	private void addDeliverFeeItem(){
		if ( copyList.size()>7 )
			return;
		
		addItem = new MarkUp();
		addItem.setType(1);
		addItem.setfId("");
		copyList.add(addItem);		 // 在复制的数据中加入  这条数据
		
		View itemView = View.inflate(homeActivity, R.layout.item_markup_lv, null);
		EditText rangeText = (EditText) itemView.findViewById(R.id.markup_range);
		EditText deliverFeeText = (EditText) itemView.findViewById(R.id.markup_delivefee);
		EditText sendupFeeText = (EditText) itemView.findViewById(R.id.markup_sendfee);
		ImageView delete = (ImageView) itemView. findViewById(R.id.deliverfee_delete);	
		//删除一条记录
		itemView.setTag(addItem);
		delete.setTag(itemView);
		delete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				View parent = (View) v.getTag();
				MarkUp obj = (MarkUp) parent.getTag();
				copyList.remove(obj);		//在复制数据中移除 这条数据
				redeceDeliverFeeItem(obj, parent);
			}
		});
		
		rangeText.setText("");
		deliverFeeText.setText("");
		sendupFeeText.setText("");
		
		//显示操作面板
		layout_deliveryfee_panel.setVisibility(View.VISIBLE);
		//删除添加按钮
		deliverContainerView.removeView(addText);
		//添加一条记录
		deliverContainerView.addView(itemView);
		if ( copyList.size()<8 ) {
			//增加一个新增区段按钮
			addView();
		}
		
	}
	
	/**
	 * 删除一条阶梯价
	 */
	private void redeceDeliverFeeItem(MarkUp up, View removeView){
		if ( copyList.size()<0 )
			return;
		
		if ( deliverContainerView!=null )
			deliverContainerView.removeView(removeView);
		
		MarkUp removeItem = new MarkUp();
		removeItem.setfId(up.getfId());
		removeItem.setDeliverFee(up.getDeliverFee());
		removeItem.setRange(up.getRange());
		removeItem.setSendUpFee(up.getSendUpFee());
		removeItem.setType(2);
		
		if ( !TextUtils.isEmpty(up.getfId()) ) {	//只有存在的阶梯价才会存入删除的list	
			removeList.add(removeItem);				//把要移除的数据加入 list
		}
		
		if ( layout_deliveryfee_panel.getVisibility()==View.GONE ) {
			//显示操作面板
			layout_deliveryfee_panel.setVisibility(View.VISIBLE);
		}
		
		//删除添加按钮
		deliverContainerView.removeView(addText);
		if ( copyList.size()<8 ) {
			//增加一个新增区段按钮
			addView();
		}
		
	}
	
	
}
